// base
import Taro, { Component } from '@tarojs/taro'
import { View, Input, ScrollView, Image } from '@tarojs/components'
import { AtActivityIndicator } from 'taro-ui'
import { connect } from '@tarojs/redux'
// redux
import { DOREQUESTCHATPAGE } from './store/actions/pagechatpage'
import { UPDATEPAGECHATPAGE } from './store/types/pagechatpage'
import { UPDATEIM } from '../../../store/types/im'
// less
import './index.less'

// componnet
import scaleImageSrc from '../../../util/pagemethods/scaleImageSrc'
import { setNavigationBarTitle } from '../../../crossplatform/apiservice/setNavigation'
import { makePhoneCall } from '../../../crossplatform/apiservice/makephonecall'
import pagejumplist from '../../../configuration/pagejumplist.json'
import { navigateTo } from '../../../crossplatform/apiservice/navigate'
import { getGlobalData } from '../../../configuration/globaldata'
import messagePush from '../../../util/messagePush'
import IMController from '../../../util/wy_im'
import { showToast } from '../../../crossplatform/apiservice/toast'
import { avater, avaterB } from '../../../configuration/staticimg'
import If from '../../../components/page-components/if'
import tool from '../../../util/tool'
import judgeBlack from '../../../util/judge_black'
import { getMemberTalentTalkRequest } from '../../../service/member-controller'
import { previewImage } from '../../../crossplatform/apiservice/media/imageView'

const imgMaxWidth = 200

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGECHATPAGE,
      payload: {
        ...payload
      }
    })
  },
  updateImState(payload) {
    dispatch({
      type: UPDATEIM,
      payload: {
        ...payload
      }
    })
  },
  dorequest() {
    return new Promise(resolve => {
      let promise = DOREQUESTCHATPAGE()
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  }
})

let DPR = getGlobalData('dpr')

@connect(
  ({ pagechatpage, im, userinfo }) => ({
    ...pagechatpage,
    ...im,
    ...userinfo
  }),
  mapActiontoProps
)
class ChatPage extends Component {
  config = {
    navigationBarTitleText: '',
    disableScroll: true
  }
  constructor(props) {
    super(props)
    this.state = {
      loginInfoState: {},
      friendInfo: {},
      value: '',
      lastMsgTime: 0, // 第一次拉取好友历史消息时，必须传0
      complete: false,
      maxCnt: 10,
      fixBtnVisible: false,
      commonHeight: 110 * DPR * 4,
      commonWordListC: [
        '你好，我对这个职位很感兴趣，方便聊聊吗？',
        '这个工作需要面试吗？',
        '请问您公司具体是做什么的？',
        '请问这个职位的薪资是如何计算的？'
      ],
      commonWordListB: [
        '你好，有兴趣聊聊吗？',
        '什么时候方便过来面试吗？',
        '不好意思，该职位已招满',
        '你好，请问还在找工作吗？'
      ],
      historyStatus: false, // 获取历史消息状态
      getMsgArr: false,
      keyBoardHeight: 0,
      keyBoardShow: false,
      scrollTop: 0
    }
  }

  componentWillMount() {
    // onLoad
    this.onShow()
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    // onshow
    const { companyId, role } = this.props
    role === 'company' && judgeBlack.getBlackCompanyIds(companyId)
  }

  componentDidHide() {
    // onhide
  }

  componentWillUnmount() {
    // onUnload
    // 初始化
    this.props.updateImState({
      // selToID: '',
      toView: ``,
      currentSessionId: ''
    })
    this.setState({
      fixBtnVisible: false,
      getMsgArr: false,
      scrollTop: 0,
      keyBoardShow: false
    })
  }

  onShow = () => {
    // 获取聊天记录
    const { selToID, loginInfo, currentSessionId } = this.props
    // 获取两个人的信息
    console.log([selToID, loginInfo.accid], '[selToID, loginInfo.accid]')
    IMController.getUsers([selToID, loginInfo.accid]).then(data => {
      if (data.length) {
        const friendInfo = data[0]
        const loginInfoState = data[1]
        setNavigationBarTitle({ title: friendInfo.nick })
        this.setState(
          {
            friendInfo,
            loginInfoState
          },
          () => {
            this.getHistoryMsgs()
          }
        )
      }
      IMController.updateUnreadInfo(currentSessionId)
    })
  }

  getHistoryMsgs = isUpper => {
    return new Promise(resolve => {
      const { lastMsgTime, maxCnt, complete } = this.state
      const { selToID, msgArray } = this.props
      if (!complete) {
        IMController.getHistoryMsgs({ selToID, maxCnt, lastMsgTime }).then(
          ({ obj, complete: isComplete }) => {
            let newMsgArray = [...obj.msgs, ...msgArray]
            this.props.updateImState({
              msgArray: newMsgArray
            })
            newMsgArray.length < 1 && this.activeSendMessage()
            this.setState({
              complete: isComplete,
              lastMsgTime: (obj.msgs[0] && obj.msgs[0].time) || new Date().getTime(),
              getMsgArr: true
            })
            let timer = setTimeout(() => {
              // 设置延迟 不然scroll-into-view 不起作用
              clearTimeout(timer)
              this.props.updateImState({
                toView: isUpper ? `chat${obj.msgs.length}` : `chat${newMsgArray.length - 1}`
              })
            }, 10)
            resolve()
          }
        )
      }
    })
  }

  onChange = e => {
    const { value } = e.detail
    this.setState({
      value
    })
  }

  inputConfirm = tool.throttle(e => {
    const { value } = e.detail
    const { role, userInfoB, userInfoC, userId } = this.props
    const { friendInfo } = this.state
    this.setState({
      value
    })
    if (value) {
      this.onSendMsg(value).then(() => {
        if (role == 'personal') {
          // C2B
          messagePush.sendMessage({
            name: userInfoC.userName,
            userId: parseInt(friendInfo.account) + '',
            content: value,
            templateType: 'advisory',
            role: 'company'
          })
          // （发布岗位主动发的消息） 记录沟通历史
          let custom = JSON.parse(friendInfo.custom)
          Object.keys(custom) &&
            Object.keys(custom).length &&
            getMemberTalentTalkRequest({
              companyId: custom.companyId,
              userId: parseInt(friendInfo.account) + '',
              cmpUserId: userId,
              type: 'B'
            })
        } else {
          // B2C
          !(friendInfo.account.indexOf('old') > -1) &&
            messagePush.sendMessage({
              name: userInfoB.userName,
              userId: parseInt(friendInfo.account) + '',
              content: value,
              templateType: 'advisory'
            })
        }
      })
    } else {
      showToast({
        title: '发送消息不能为空'
      })
    }
  })

  activeSendMessage = () => {
    // 如果没有发过消息 则主动发消息
    const { role } = this.props
    const msg =
      role === 'personal'
        ? '你好，我对这个职位很有兴趣，方便的话可以聊聊吗？'
        : `你好，方便的话可以聊聊吗？`
    this.onSendMsg(msg)
  }

  onSendMsg = value => {
    return new Promise(resolve => {
      const { selToID } = this.props
      this.setState({
        value: ''
      })
      IMController.sendMsg({ selToID, value }).then(() => {
        const { msgArray } = this.props
        this.props.updateImState({
          toView: `chat${msgArray.length - 1}`
        })
        resolve()
      })
    })
  }

  onScrollToUpper = () => {
    // 继续获取历史消息
    const { historyStatus } = this.state
    if (!historyStatus) {
      this.props.updateImState({
        toView: ``
      })
      this.setState({
        historyStatus: true
      })
      const { complete } = this.state
      if (!complete) {
        this.getHistoryMsgs(true).then(() => {
          this.setState({
            historyStatus: false
          })
        })
      }
    } else {
    }
  }

  setDefaultHeadUrl = (role, gender, userId = 0) => {
    return role === 'personal' ? avaterB(gender) : avater(gender, userId)
  }

  callPhone = () => {
    // 打电话
    const {
      friendInfo: { tel }
    } = this.state
    if (this.judgeCanCallPhone()) {
      makePhoneCall({ phoneNumber: tel })
    } else {
      showToast({
        title: '只有双方沟通过才能打电话'
      })
    }
  }

  judgeCanCallPhone = () => {
    // 判断是否两人都发送过消息 true： 可打电话
    const {
      selToID,
      loginInfo: { accid },
      msgArray = []
    } = this.props
    let isFrom = false // 别人主动发
    let isTo = false // 自己主动发
    let flag = false
    msgArray.map(item => {
      if (item.from === selToID && item.to === accid) {
        isFrom = true
      }
      if (item.to === selToID && item.from === accid) {
        isTo = true
      }
      if (isFrom && isTo) {
        flag = true
      }
    })
    return flag
  }

  getCommonWord = () => {
    // 常用语
    const { fixBtnVisible } = this.state
    if (fixBtnVisible) {
      this.hideCommonWord()
    } else {
      this.showCommonWord()
    }
  }

  hideCommonWord = () => {
    // 常用语隐藏
    this.setState({
      fixBtnVisible: false
    })
    let timer = setTimeout(() => {
      clearTimeout(timer)
      this.setState({
        scrollTop: 99999999
      })
    }, 300)
  }

  showCommonWord = () => {
    // 常用语展示
    this.setState({
      fixBtnVisible: true
    })
    let timer = setTimeout(() => {
      clearTimeout(timer)
      this.setState({
        scrollTop: 999999
      })
    }, 300)
  }

  setCommonWord = tool.throttle(e => {
    let value = e.currentTarget.dataset.value
    const { role, userInfoB, userInfoC } = this.props
    const { friendInfo } = this.state
    this.onSendMsg(value).then(() => {
      if (role == 'personal') {
        // C2B
        messagePush.sendMessage({
          name: userInfoC.userName,
          userId: parseInt(friendInfo.account) + '',
          content: value,
          templateType: 'advisory',
          role: 'company'
        })
      } else {
        // B2C
        !(friendInfo.account.indexOf('old') > -1) &&
          messagePush.sendMessage({
            name: userInfoB.userName,
            userId: parseInt(friendInfo.account) + '',
            content: value,
            templateType: 'advisory'
          })
      }
    })
    this.hideCommonWord()
  })

  goFriendPage = () => {
    // 跳转个人主页
    navigateTo({
      url: `${pagejumplist['person-detail'].path}?userId=${'262208'}`
    })
  }

  onInputFocus = e => {
    // input 输入框获取焦点
    const { height } = e.detail
    const { fixBtnVisible } = this.state
    if (fixBtnVisible) {
      this.hideCommonWord()
    }
    this.setState({
      keyBoardHeight: height + 65,
      keyBoardShow: true
    })
    let timer = setTimeout(() => {
      clearTimeout(timer)
      this.setState({
        scrollTop: 999999
      })
    }, 300)
  }

  onInputBlur = () => {
    this.setState({
      keyBoardHeight: 0,
      keyBoardShow: false
    })
    let timer = setTimeout(() => {
      clearTimeout(timer)
      this.setState({
        scrollTop: 99999999
      })
    }, 300)
  }

  renderChat(item) {
    // 渲染图片信息
    const { value: url = '', width = 0, height = 0 } = item
    let textStyle = {}
    if (width > imgMaxWidth) {
      // 大于imgMaxWidth 则进行缩放
      textStyle = { width: `${imgMaxWidth}px`, height: `${(height * imgMaxWidth) / width}px` }
    } else {
      textStyle = { width: `${width}px`, height: `${height}px` }
    }
    return (
      <Image
        className="chat-item-text"
        style={textStyle}
        src={url}
        mode="aspectFill"
        data-url={url}
        onClick={this._previewImg}
      />
    )
  }

  _previewImg = e => {
    let { url } = e.currentTarget.dataset
    previewImage({
      current: url,
      urls: [url]
    })
  }

  render() {
    const {
      value,
      loginInfoState,
      friendInfo,
      commonWordListC,
      commonWordListB,
      fixBtnVisible,
      getMsgArr,
      commonHeight,
      keyBoardHeight,
      keyBoardShow,
      scrollTop
    } = this.state
    const { msgArray, toView, role } = this.props
    let commonList = role == 'personal' ? commonWordListC : commonWordListB
    let scrollViewHeight = fixBtnVisible ? commonHeight + 65 : 65
    let keyBoard = keyBoardShow ? keyBoardHeight : 65
    return (
      <View className="ChatPage_id90234">
        <ScrollView
          className="chat-content"
          style={`height: calc(100vh - ${Math.max(scrollViewHeight, keyBoard)}px);`}
          scrollY
          scrollIntoView={toView}
          onScrollToUpper={this.onScrollToUpper}
          scrollTop={scrollTop}
        >
          <View className="chat-item-container">
            <If
              visible={getMsgArr || (msgArray && msgArray.length)}
              renderElse={<AtActivityIndicator content="加载中..." mode="center" />}
            >
              {msgArray &&
                msgArray.length &&
                msgArray.map((item, index) => {
                  let userAvatar =
                    friendInfo.avatar ||
                    this.setDefaultHeadUrl(
                      role,
                      friendInfo.gender,
                      friendInfo.account ? parseInt(friendInfo.account) : 0
                    )
                  let userAvatarMine =
                    loginInfoState.avatar ||
                    this.setDefaultHeadUrl(
                      role === 'personal' ? 'company' : 'personal',
                      loginInfoState.gender,
                      loginInfoState.account ? parseInt(loginInfoState.account) : 0
                    )
                  return !item.isSelf ? (
                    <View id={`chat${index}`} className="chat-container">
                      <If visible={item.displayTimeHeader}>
                        <View className="chat-time">{item.displayTimeHeader}</View>
                      </If>

                      <View className="chat-item chat-item-other">
                        <Image
                          className="chat-item-head"
                          src={scaleImageSrc(userAvatar, 90)}
                          mode="aspectFill"
                          // onClick={this.goFriendPage}
                        />
                        {
                          item.type === 'image' ? this.renderChat(item) : <View className="chat-item-text">{item.value}</View>
                        }
                      </View>
                    </View>
                  ) : (
                    <View id={`chat${index}`} className="chat-container">
                      <If visible={item.displayTimeHeader}>
                        <View className="chat-time">{item.displayTimeHeader}</View>
                      </If>
                      <View
                        className={`chat-item ${
                          role == 'company' ? 'chat-item-self' : 'chat-item-c'
                        }`}
                      >
                        {
                          item.type === 'image' ? this.renderChat(item) : <View className="chat-item-text">{item.value}</View>
                        }
                        <Image
                          className="chat-item-head"
                          src={scaleImageSrc(userAvatarMine, 90)}
                          mode="aspectFill"
                        />
                      </View>
                    </View>
                  )
                })}
            </If>
          </View>
        </ScrollView>
        <View className="bottom-fix">
          <View className="bottom-fix-input">
            <View className="common-word" onClick={this.getCommonWord}>
              常用语
            </View>
            <Input
              className="textarea-item"
              value={value}
              name="input"
              onInput={this.onChange}
              onConfirm={this.inputConfirm}
              onFocus={this.onInputFocus}
              onBlur={this.onInputBlur}
              placeholder="请输入消息..."
              confirmType="send"
              confirm-hold
              adjustPosition={false}
            />
            <View className="bottom-call" onClick={this.callPhone}>
              <Image
                src={
                  this.judgeCanCallPhone()
                    ? 'https://imagesize.hrwork.com/sp/files/624fa7a6-929d-438a-b722-6950ce2ccb93.png'
                    : 'https://imagesize.hrwork.com/sp/files/e1c1176b-4385-4b7b-acee-07ccbbee5007.png'
                }
              />
            </View>
          </View>
        </View>
        {fixBtnVisible && (
          <View className="common-container">
            {commonList &&
              commonList.map((item, index) => {
                return (
                  <View
                    className="common-item"
                    key={index}
                    data-value={item}
                    onClick={this.setCommonWord}
                  >
                    {item}
                  </View>
                )
              })}
          </View>
        )}
      </View>
    )
  }
}

export default ChatPage
